package stancel.peter.smslogger.activities;

import java.util.ArrayList;
import java.util.List;

import stancel.peter.smslogger.ListAdapter;
import stancel.peter.smslogger.R;
import stancel.peter.smslogger.SMSLogger;
import stancel.peter.smslogger.Sms;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.SmsManager;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

/**
 * Zobrazuje prijate SMS.
 * @author Peter Stancel
 */
public class MainActivity extends Activity implements OnClickListener{

	private SMSLogger smsLogger;
	private ListAdapter listAdapter;
	/** List vsetkych uz nacitanych SMS zo suborov. */
	private List<Sms> listOfLoadedSms;
	/** List SMS, ktore su prave zobrazene na obrazovke zariadenia */
	private List<Sms> list;
	/** Cislo suboru, s ktorym aplikacia aktualne pracuje. */
	private int fileNumber;
	/** Cislo urcujuce 1. zobrazenu SMS v liste <i>list</i> */
	private int smsNumber;
	/** Pocet SMS-iek zobrazenych na jednej strane */
	private int numberOfSms;
	private Button buttonNext;
	private Button buttonPrevious;
	private TextView displayedSms;
	private SharedPreferences preferences;

	/**
	 * Vola sa pri vytvarani tejto aktivity.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		smsLogger = (SMSLogger) getApplication();
		fileNumber = smsLogger.getMaxFileNumber();
		// nacita posledny subor s najaktualnejsimi sms
		listOfLoadedSms = smsLogger.loadFromFile(fileNumber);
		
		list = new ArrayList<Sms>();
		smsNumber = 0;
		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		numberOfSms = Integer.valueOf(preferences.getString("smslogger_preferences_number_of_sms", "50"));
		
		displayedSms = (TextView) findViewById(R.id.text_displayedsms);
		buttonNext = (Button) findViewById(R.id.button_next);
		buttonPrevious = (Button) findViewById(R.id.button_previous);
		buttonNext.setOnClickListener(this);
		buttonPrevious.setOnClickListener(this);
		ListView listView = (ListView) findViewById(R.id.listView);

		listAdapter = new ListAdapter(this, list);
		listView.setAdapter(listAdapter);
		
		
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notificationManager.cancel(11223);
		registerForContextMenu(listView);
	}
	
	/**
	 * Vola sa pri starte aktivity.
	 */
	@Override
	protected void onStart() {
		super.onStart();
		getSms();
	}

	/**
	 * Naplni <i>list</i> s SMS ziskane zo suboru.
	 * Ak bude potrebne, zabezpeci nacitanie dalsich SMS z
	 * nasledujuceho suboru.
	 */
	private void getSms() {
		list.clear();
		StringBuilder builder = new StringBuilder();
		
		if(listOfLoadedSms.isEmpty()){
			builder.append(smsNumber + " - ");
		} else {
			builder.append((smsNumber + 1) + " - ");
		}
		
		int i;
		for(i = 0; i < numberOfSms; i++){
			if(listOfLoadedSms.size() > i + smsNumber && i + smsNumber >= 0){
				list.add(listOfLoadedSms.get(smsNumber + i));
			}else {
				if(fileNumber > 1){
					// nacitanie starsieho suboru a ulozenie sprav do listu vsetkych uz nacitanych SMS
					fileNumber--;
					for (Sms sms : smsLogger.loadFromFile(fileNumber)) {
						listOfLoadedSms.add(sms);
					}
					i--;
				} else {
					break;
				}
			}
		}
		displayedSms.setText(builder.append(smsNumber + i).toString());
	}

	/**
	 * Po stlaceni tlacidla:
	 * <i>button_next</i> - nacita nasledujuce SMS,
	 * <i>button_previous</i> - nacita predchadzajuce SMS.
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button_next:
			if(listOfLoadedSms.size() > smsNumber + numberOfSms || fileNumber > 1){
				smsNumber = smsNumber + numberOfSms;
			}
			break;
		case R.id.button_previous:
			if(smsNumber > 0){
				smsNumber = smsNumber - numberOfSms;
				if(smsNumber < 0){
					smsNumber = 0;
				}
			}
			break;
		}
		getSms();
		listAdapter.notifyDataSetChanged();
	}
	
	/**
	 * Vola sa pri stlaceni tlacidla Menu na zariadeni.
	 * Vytvara Hlavne menu.
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_option_main_activity, menu);
		return true;
	}
	
	/**
	 * Podla vybraneho itemu v OptionsMenu spusti danu Aktivitu:
	 * <i>settings</i> - spusti aktivitu <b>SettingsActivity</b>,
	 * <i>contacts</i> - spusti aktivitu <b>ContactsActivity</b>,
	 * <i>about</i> - spusti aktivitu <b>AboutActivity</b>.
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		switch (item.getItemId()) {
			case (R.id.settings): {
				Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
				startActivity(intent);
				return true;
			}
			case (R.id.contacts): {
				Intent intent = new Intent(MainActivity.this, ContactsActivity.class);
				startActivity(intent);
				return true;
			}
			case (R.id.about): {
				Intent intent = new Intent(MainActivity.this, AboutActivity.class);
				startActivity(intent);
				return true;
			}
		}
		return false;
	}
	
	/**
	 * Vola sa pri dlhom stlaceni SMS.
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		
		menu.setHeaderTitle(R.string.selected_sms);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_context_main, menu);
	}
	
	/**
	 * Podla zvolenej moznosti vykona operaciu nad SMS:
	 * <i>call</i> - zavola na cislo prijatej SMS,
	 * <i>send_sms</i> - vytvori dialog a posle spravu na cislo prijate SMS.
	 */
	@Override
	public boolean onContextItemSelected(MenuItem item) {

		AdapterView.AdapterContextMenuInfo menuInfo;
		menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
		final int index = menuInfo.position;
		switch (item.getItemId()) {
			case (R.id.call): {
				Intent intent = new Intent(Intent.ACTION_CALL);
				intent.setData(Uri.parse("tel:" + list.get(index).getPhoneNumber()));
				startActivity(intent);
				return true;
			}
			case (R.id.send_sms): {
				final EditText message = new EditText(this);
				message.setBackgroundResource(R.drawable.contact_filter_background);
				String title = getString(R.string.send_sms) + " to ";
				final Sms sms = list.get(index);
				if(sms.getName() == null){
					title += sms.getPhoneNumber();
				}else title += sms.getName();
				new AlertDialog.Builder(this).setTitle(title).setIcon(android.R.drawable.ic_dialog_email).setMessage(
						R.string.message).setView(message).setPositiveButton(
						R.string.send_sms, new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {        
								SmsManager smsManager = SmsManager.getDefault();
							    smsManager.sendTextMessage(sms.getPhoneNumber(), null, message.getText().toString(), null, null); 
							}
						}).setNegativeButton(android.R.string.cancel, null).show();
				return true;
			}
		}
		return false;
	}

	/**
	 * Vola sa, ak sa aktivita vratila spat do popredia.
	 */
	@Override
	protected void onResume() {
		super.onResume();
		fileNumber = smsLogger.getMaxFileNumber();
		listOfLoadedSms = smsLogger.loadFromFile(fileNumber);
		numberOfSms = Integer.valueOf(preferences.getString("smslogger_preferences_number_of_sms", "50"));
		getSms();
		listAdapter.notifyDataSetChanged();
	}
}